<template>
	<view class="container">
		<!-- 顶部导航 -->
		<!--  <u-navbar
      title="账单明细"
      :autoBack="true"
      bgColor="#ffffff"
    ></u-navbar> -->

		<!-- 时间选择 -->
		<view class="time-filter">
			<uni-datetime-picker v-model="currentTime" type="datetimerange" @change="handleTimeConfirm($event)" />
		</view>

		<!-- 统计卡片 -->
		<!--  <view class="stats-cards">
      <u-card>
        <view class="stats-item">
          <text class="label">总收入</text>
          <text class="value income">+￥{{ totalIncome }}</text>
        </view>
        <view class="stats-item">
          <text class="label">总支出</text>
          <text class="value expense">-￥{{ totalExpense }}</text>
        </view>
        <view class="stats-item">
          <text class="label">结余</text>
          <text class="value">￥{{ totalBalance }}</text>
        </view>
      </u-card>
    </view> -->

		<!-- 分类筛选 -->
		<!--   <u-tabs
      :list="categoryList"
      :current="currentCategory"
      @change="handleCategoryChange"
      lineColor="#2979ff"
      :activeStyle="{ color: '#2979ff' }"
    ></u-tabs> -->

		<!-- 账单列表 -->
		<scroll-view scroll-y class="bill-list" style="height: 85vh;padding-top: 20rpx;" @scrolltolower="loadMore">
			<view class="listNull" v-if="filteredBills.length == 0">
				<img src="@/static/images/listNull.png" alt="" />
				<text>暂无账单</text>
			</view>
			<u-list>
				<u-list-item v-for="(item, index) in filteredBills" :key="index">
					<view class="bill-item">
						<view class="stats-cards">
							<view class="stats-item">
								<text class="label">总收入</text>
								<text class="value income">+￥{{ item.sellAmount }}</text>
							</view>
							<view class="stats-item">
								<text class="label">总支出</text>
								<text class="value expense">-￥{{ item.outAmount }}</text>
							</view>
							<view class="stats-item">
								<text class="label">总结余</text>
								<text class="value">￥{{ item.amount }}</text>
							</view>
						</view>
						<view class="stats-cards">
							<view class="stats-item">
								<text class="label">收入</text>
								<text class="value income">+￥{{ item.sellCoin }}</text>
							</view>
							<view class="stats-item">
								<text class="label">支出</text>
								<text class="value expense">-￥{{ item.outAmount }}</text>
							</view>
							<view class="stats-item">
								<text class="label">结余</text>
								<text class="value">￥{{ item.outCoin }}</text>
							</view>
						</view>
						<view class="left">
							<text class="remark">备注：{{ item.description || '无备注' }}</text>
						</view>
						<view class="right">
							<text class="time">{{ item.editTime }}</text>
						</view>
					</view>
				</u-list-item>
			</u-list>

			<!-- 空状态 -->
			<u-empty v-if="filteredBills.length === 0" mode="list"></u-empty>

			<!-- 加载状态 -->
			<u-loadmore :status="loadingState" icon-type="circle" />
		</scroll-view>

		<!-- 分页控件 -->
		<u-pagination v-model="page" :page-count="pageCount" :total="pageTotal" mode="button" @change="pageChange" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue'
	import API from "@/api/index.js"
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		contains
	} from '../../../uni_modules/uview-plus/libs/function/test';

	// 时间选择
	const showTimePicker = ref(false)
	const currentTime = ref([Date.now() - 1000000000, Date.now()])
	let page = ref(1)
	let pageSize = ref(10)
	let pageTotal = ref(10)
	let loading = ref(false)
	let loadingState = ref('loadmore')

	// 计算总页数
	const pageCount = computed(() => {
		return Math.ceil(pageTotal.value / pageSize.value)
	})
	onLoad(() => {
		getList(1)
	})

	let filteredBills = reactive([])

	let condition = reactive([{
		"filedIndex": "uid",
		"filedValue": uni.getStorageSync('userInfo').id
	}])

	// 获取列表
	const getList = async (index) => {
		// 处理中condition中为null的数据
		const conditionArray = condition.filter(item => item !== null);
		console.log("conditionArray", conditionArray);
		try {
			loadingState.value = 'loading'
			let res = await API.OilObtainSummaryList({
				"pageIndex": index,
				"pageSize": 10,
				"condition": conditionArray
				// "condition": [
				//     {
				//         "filedIndex": "string",
				//             "filedValue": "string"
				//     }
				//   ]
			})

			console.log("getList res", res.data.list);
			if (index == 1) {
				filteredBills.length = 0
				Object.assign(filteredBills, res.data.list)
			} else {
				filteredBills.push(...res.data.list)
			}
			pageTotal.value = res.data.total
			page.value = res.data.currentPage
			loadingState.value = filteredBills.length >= pageTotal.value ? 'nomore' : 'loadmore'
		} catch (e) {
			loadingState.value = 'error'
		}
	}
	// 页码变化
	const pageChange = (page) => {
		page.value = page
		console.log("页码变化了", page.value);
		getList(page.value)
	}
	// 加载更多（滚动到底部）
	const loadMore = () => {
		console.log("滚动到底了");
		console.log(page.value, pageCount.value);
		if (page.value < pageCount.value) {
			page.value++
			setTimeout(() => {
				getList(page.value)
			}, 1000)
		}
	}
	// 时间格式处理
	const formatDate = (timestamp, format = 'YYYY-MM') => {
		if (!timestamp) return ''

		const date = new Date(Number(timestamp))
		if (isNaN(date)) return ''

		const pad = n => n.toString().padStart(2, '0')

		const timeObj = {
			YYYY: date.getFullYear(),
			MM: pad(date.getMonth() + 1),
			DD: pad(date.getDate()),
			HH: pad(date.getHours()),
			mm: pad(date.getMinutes()),
			ss: pad(date.getSeconds())
		}

		return format.replace(/(YYYY|MM|DD|HH|mm|ss)/g, match => timeObj[match])
	}
	// 方法
	const handleTimeConfirm = (time) => {
		console.log('选择的时间：', time, currentTime.value)
		if(time.length==0){
			condition[1] = {
				"filedIndex": "date",
				"filedValue": null
			}
		}else{
			currentTime.value[0] = time[0]
			currentTime.value[1] = time[1]
			condition[1] = {
				"filedIndex": "date",
				"filedValue": time.toString()
			}
		}
		getList(1)
	}

	const handleCategoryChange = (index) => {
		currentCategory.value = index
	}
</script>

<style lang="scss" scoped>
	.listNull {
		display: flex;
		flex-direction: column;
		text-align: center;
		margin: 0 auto;

		image {
			width: 200rpx;
			height: 200rpx;
			// margin: 10% 0 10% 10%;
			margin: 20rpx auto;
		}

		text {
			color: #919ea9;
		}
	}

	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.time-filter {
		margin: 20rpx 0;
		text-align: center;
	}

	.stats-cards {
		display: flex;
		width: 100vw;
		justify-content: space-evenly;

		// margin: 20rpx 0;
		margin-bottom: 20rpx;

		.stats-item {
			display: flex;
			justify-content: space-between;
			padding: 20rpx;

			.label {
				color: #666;
			}

			.value {
				font-weight: bold;

				&.income {
					color: #19be6b;
				}

				&.expense {
					color: #ff0000;
				}
			}
		}
	}

	.bill-list {
		// height: calc(100vh - 400rpx);

		.bill-item {
			display: flex;
			box-shadow: 0px 0px 5px 0px #cccbcb;
			justify-content: space-between;
			flex-direction: column;
			align-items: center;
			padding: 30rpx;
			background: white;
			margin-bottom: 20rpx;
			border-radius: 10rpx;

			.left {
				width: 90vw;
				// display: flex;
				// align-items: center;

				.remark {
					color: #999;
					font-size: 28rpx;
				}
			}

			.right {
				text-align: right;
				width: 90vw;

				.time {
					color: #999;
					font-size: 24rpx;
				}
			}
		}
	}
</style>